package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 过滤器类型:pre,routing,post,error
     *
     */
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    /*
    位置顺序号，zuul的前置过滤器默认有5个
    */
    @Override
    public int filterOrder() {
        return 6;
    }

    /*
    判读针对当前请求，是否要执行过滤代码
    */
    @Override
    public boolean shouldFilter() {
        /*
        调用item-service 需要检查权限；
        调用其他服务不判断权限，可以直接访问
        */
        //获取当前服务请求调用的服务id
        RequestContext ctx = RequestContext.getCurrentContext();//上下文对象
        String serviceId =(String) ctx.get(FilterConstants.SERVICE_ID_KEY);//获得serviceId

        //判断id是不是"item-service"
        return "item-service".equalsIgnoreCase(serviceId);

    }

    /*
    过滤代码
    */
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/yyww?token=u645t

        //得到request 对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        //用request 接受token参数
        String token = request.getParameter("token");

        //如果收不到 token，阻止向后台服务转发，直接向客户端返回响应
        if(StringUtils.isBlank(token)){
            //阻止向后台服务转发
            ctx.setSendZuulResponse(false);

            //向客户端直接发送响应:JsonResult={code:400,msg:"not login!",data:null}
            String json = JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("Not Login! 没有登录！")
                    .toString();

            //http 协议头属性: Content-Type：application/json;charset=UTF-8
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }

      return null;
    }
}
